﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Weazel.Willows.InterfaceGeneration
{
	public class MemoryMap
	{
		Dictionary<int, MemoryMappedItem> map;

		/// <summary>
		/// Get the memory mapped item at a given
		/// position
		/// </summary>
		/// <param name="index"></param>
		/// <returns>Memory mapped item at position</returns>
		public MemoryMappedItem this[int index]
		{
			get
			{
				return map[index];
			}
			set
			{
				map[index] = value;
			}
		}

		public int AddressesNeeded
		{
			get
			{
				return map.Count;
			}
		}

		/// <summary>
		/// List of items in this memory map
		/// </summary>
		public List<MemoryMappedItem> Items
		{
			get
			{
				List<MemoryMappedItem> items = new List<MemoryMappedItem>();
				foreach (MemoryMappedItem item in map.Values)
					items.Add(item);

				return items;
			}
		}

		/// <summary>
		/// Assign a memory mapped item to one or more addresses
		/// </summary>
		/// <param name="item"></param>
		/// <param name="baseAddress"></param>
		/// <param name="count"></param>
		public void Assign(MemoryMappedItem item, int baseAddress, int count)
		{
			for (int i = 0; i < count; i++)
				map.Add(baseAddress + i, item);
		}

		public MemoryMap()
		{
			this.map = new Dictionary<int, MemoryMappedItem>();
		}

		public override string ToString()
		{
			StringBuilder str = new StringBuilder();
			str.AppendLine("Memory map");

			foreach (int address in map.Keys)
			{
				str.AppendLine(string.Format("{0}\t: {1}", address, map[address].ToString()));
			}

			return str.ToString();
		}
	}
}
